<?php

namespace support\spark\plugin\helpers;

use support\spark\model\system\AdminNode;

class Menu
{
    /**
     * 删除菜单
     * @param $key
     * @return void
     */
    public static function delete($type)
    {
        return AdminNode::where('type', $type)->delete();
    }

    /**
     * 根据key获取菜单
     * @param $key
     * @return array
     */
    public static function get($path)
    {
        $menu = AdminNode::where('path', $path)->first();
        return $menu ? $menu->toArray() : [];
    }

    /**
     * 根据id获得菜单
     * @param $id
     * @return array
     */
    public static function find($id): array
    {
        return AdminNode::find($id)->toArray();
    }


    /**
     * 添加菜单
     * @param array $menu
     * @return int
     */
    public static function add(array $menu)
    {
        $item = new AdminNode;
        foreach ($menu as $key => $value) {
            $item->$key = $value;
        }
        $item->save();
        return $item->id;
    }

    /**
     * 导入菜单
     * @param array $menu_tree
     * @return void
     */
    public static function import(array $menu_tree,string $type,$pid=0)
    {
       if(!$menu_tree ) return;
       foreach ($menu_tree as $item){
           $children = $item['children'] ?? [];
           unset($item['children']);
           $item['pid'] =$pid;
           $item['type'] =$type;
           $old_menu = Menu::get($item['path']);
           if ($old_menu && $item['path'] !='#') {
               $npid = $old_menu['id'];
               AdminNode::where('path', $item['path'])->update($item);
           }else{
               $npid = static::add($item);
           }
           static::import($children,$type,$npid);
       }

    }
}
